import { defineStore } from 'pinia'
import { scriptApi, userApi } from '../api'

interface Script {
  id: number
  nodenum: number
  content: string
  answernum: number
  next_answernum: number | null
  answertype: 'T' | 'C' | 'I'  // T=系统文本, C=用户选择, I=用户输入
  need_input: number
  timer?: number | null  // 计时器（秒）
  created_at: string
  updated_at: string
}

interface QuestionState {
  currentChapter: number
  currentAnswerNum: number
  scripts: Script[]
  currentQuestions: Script[]
  history: number[]
  isLoading: boolean
}

export const useQuestionStore = defineStore('question', {
  state: (): QuestionState => ({
    currentChapter: 1,
    currentAnswerNum: 1,
    scripts: [],
    currentQuestions: [],
    history: [],
    isLoading: false
  }),

  getters: {
    // 获取当前显示的问题组（相同answernum的问题）
    getCurrentGroup: (state) => {
      return state.scripts.filter(script => 
        script.answernum === state.currentAnswerNum
      )
    },

    // 获取系统文本（T类型）
    getSystemTexts: (state) => (answernum: number) => {
      return state.scripts.filter(script => 
        script.answernum === answernum && script.answertype === 'T'
      )
    },

    // 获取选择选项（C类型）
    getChoices: (state) => (answernum: number) => {
      return state.scripts.filter(script => 
        script.answernum === answernum && script.answertype === 'C'
      )
    },

    // 检查是否需要输入框（检查所有类型的记录）
    getNeedInput: (state) => (answernum: number) => {
      const allScripts = state.scripts.filter(script => 
        script.answernum === answernum
      )
      const needInput = allScripts.some(script => script.need_input === 1)
      console.log(`🔍 检查问题${answernum}是否需要输入框:`, {
        scriptsCount: allScripts.length,
        scripts: allScripts.map(s => ({ id: s.id, type: s.answertype, need_input: s.need_input })),
        needInput
      })
      return needInput
    },

    // 检查是否是章节结束
    isChapterEnd: (state) => {
      const currentGroup = state.scripts.filter(script => 
        script.answernum === state.currentAnswerNum
      )
      return currentGroup.some(script => script.next_answernum === 0)
    }
  },

  actions: {
    // 加载章节脚本
    async loadChapterScripts(nodenum: number, startNum?: number) {
      this.isLoading = true
      try {
        const response = await scriptApi.getChapterScripts(nodenum)
        
        if (response.success) {
          this.scripts = response.data
          this.currentChapter = nodenum
          this.currentAnswerNum = startNum || 1
          this.history = []
          return { success: true }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('加载章节脚本失败:', error)
        return { success: false, message: '加载失败，请重试' }
      } finally {
        this.isLoading = false
      }
    },

    // 选择答案，跳转到下一个问题
    selectAnswer(scriptId: number) {
      const selectedScript = this.scripts.find(s => s.id === scriptId)
      
      if (selectedScript && selectedScript.next_answernum !== null) {
        // 记录历史
        this.history.push(this.currentAnswerNum)
        
        if (selectedScript.next_answernum === 0) {
          // next_answernum为0，直接退出界面并保存当前进度
          console.log(`选择指向0，当前问题${selectedScript.answernum}，需要退出并保存进度`)
          
          return { 
            finished: true, 
            saveProgressAt: selectedScript.answernum,  // 保存当前问题编号
            needExit: true
          }
        } else {
          // 跳转到下一个问题
          const nextAnswerNum = selectedScript.next_answernum
          this.currentAnswerNum = nextAnswerNum
          return { finished: false, nextQuestion: nextAnswerNum }
        }
      }
      
      return { finished: false }
    },

    // 处理用户输入（用于需要输入框的问题）
    handleUserInput(_userInput: string) {
      // 记录历史
      this.history.push(this.currentAnswerNum)
      
      // 查找当前问题组中所有脚本
      const allScripts = this.scripts.filter(script => 
        script.answernum === this.currentAnswerNum
      )
      
      console.log(`📝 处理输入 - 问题${this.currentAnswerNum}:`, {
        scriptsCount: allScripts.length,
        scripts: allScripts.map(s => ({ 
          id: s.id, 
          type: s.answertype, 
          next_answernum: s.next_answernum,
          need_input: s.need_input 
        }))
      })
      
      // 查找有 next_answernum 的脚本
      const scriptsWithNext = allScripts.filter(script => 
        script.next_answernum !== null && script.next_answernum !== undefined
      )
      
      // 按优先级排序：I类型 > T类型 > C类型
      const sortedScripts = scriptsWithNext.sort((a, b) => {
        const priority = { 'I': 0, 'T': 1, 'C': 2 }
        return (priority[a.answertype] || 99) - (priority[b.answertype] || 99)
      })
      
      console.log(`   找到 ${sortedScripts.length} 个有next_answernum的脚本`)
      
      if (sortedScripts.length > 0) {
        const nextAnswerNum = sortedScripts[0].next_answernum
        
        if (nextAnswerNum === 0) {
          // next_answernum为0，直接退出界面并保存当前进度
          console.log(`   输入后指向0，需要退出并保存进度`)
          
          return { 
            finished: true, 
            saveProgressAt: this.currentAnswerNum,  // 保存当前问题编号
            needExit: true
          }
        } else if (nextAnswerNum !== null) {
          // 跳转到下一个问题
          console.log(`   输入后跳转：${this.currentAnswerNum} -> ${nextAnswerNum}`)
          this.currentAnswerNum = nextAnswerNum
          return { finished: false, nextQuestion: nextAnswerNum }
        }
      }
      
      console.error(`❌ 问题${this.currentAnswerNum}没有找到有效的next_answernum，无法继续`)
      console.error(`   当前问题的所有脚本:`, allScripts)
      return { finished: false }
    },

    // 重置问答状态
    reset() {
      this.currentChapter = 1
      this.currentAnswerNum = 1
      this.scripts = []
      this.currentQuestions = []
      this.history = []
    },

    // 返回上一个问题
    goBack() {
      if (this.history.length > 0) {
        this.currentAnswerNum = this.history.pop()!
        return true
      }
      return false
    },

    // 保存用户当前位置到记录数组
    async saveCurrentPosition(userId: number) {
      try {
        const response = await userApi.updateRememberPosition(
          userId, 
          this.currentChapter, 
          this.currentAnswerNum // 保存当前题目编号
        )
        
        if (response.success) {
          console.log(`✅ 保存位置成功: 章节${this.currentChapter}, 问题${this.currentAnswerNum}`)
          return { success: true }
        } else {
          console.error('保存位置失败:', response.message)
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('保存位置错误:', error)
        return { success: false, message: '保存位置失败' }
      }
    },

    // 保存用户选择答案后的下一题位置
    async saveNextPosition(userId: number, nextAnswerNum: number) {
      try {
        const response = await userApi.updateRememberPosition(
          userId, 
          this.currentChapter, 
          nextAnswerNum // 保存下一题编号
        )
        
        if (response.success) {
          console.log(`✅ 保存下一题位置成功: 章节${this.currentChapter}, 问题${nextAnswerNum}`)
          return { success: true }
        } else {
          console.error('保存下一题位置失败:', response.message)
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('保存下一题位置错误:', error)
        return { success: false, message: '保存下一题位置失败' }
      }
    },

    // 章节完成时重置该章节记录为1
    async resetChapterPosition(userId: number, nodenum: number) {
      try {
        const response = await userApi.updateRememberPosition(
          userId, 
          nodenum, 
          1 // 重置为第1题
        )
        
        if (response.success) {
          console.log(`✅ 章节${nodenum}完成，重置记录位置为1`)
          return { success: true }
        } else {
          console.error('重置位置失败:', response.message)
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('重置位置错误:', error)
        return { success: false, message: '重置位置失败' }
      }
    },

    // 获取用户在指定章节的记录位置
    async getRememberPosition(userId: number, nodenum: number) {
      try {
        // 先加载章节所有脚本来确定最大问题编号
        await this.loadChapterScripts(nodenum, 1)
        const maxAnswerNum = Math.max(...this.scripts.map(s => s.answernum))
        
        const response = await userApi.getRememberPosition(userId)
        
        if (response.success && Array.isArray(response.data)) {
          const chapterRecord = response.data.find(item => item.node === nodenum)
          let savedNum = chapterRecord ? chapterRecord.num : 1
          
          // 如果保存的是0或者大于等于最大问题编号，从第1题开始
          if (savedNum <= 0 || savedNum >= maxAnswerNum) {
            console.log(`📍 章节${nodenum}记录位置${savedNum}已完成或无效，从第1题重新开始`)
            return { success: true, startNum: 1 }
          } else {
            // 否则从下一题开始（savedNum + 1）
            const startNum = savedNum + 1
            console.log(`📍 章节${nodenum}记录位置${savedNum}，从第${startNum}题继续`)
            return { success: true, startNum }
          }
        } else {
          console.log(`📍 章节${nodenum}无记录，从第1题开始`)
          return { success: true, startNum: 1 }
        }
      } catch (error) {
        console.error('获取记录位置错误:', error)
        return { success: true, startNum: 1 } // 出错时默认从1开始
      }
    }
  }
})
